package com.example.cafe.work.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.cafe.work.dto.Result;
import com.example.cafe.work.model.Coffee;
import com.example.cafe.work.mapper.CoffeeMapper;
import com.example.cafe.work.model.StateEnum;
import com.example.cafe.work.service.CoffeeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.cafe.work.util.Uuid;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hua
 * @since 2024-09-16
 */
@Service
public class CoffeeServiceImpl extends ServiceImpl<CoffeeMapper, Coffee> implements CoffeeService {

    @Resource
    CoffeeMapper coffeeMapper;



    @Override
    public Result insert(Coffee coffee) {
        QueryWrapper<Coffee> wrapper = new QueryWrapper<>();
        String cofName = coffee.getCofName();
        //拿到coffee之后，这时候是没有id的，先查询名字是否有重复
        wrapper.eq("cof_name",cofName);
        Optional<Coffee> optional = Optional.ofNullable(coffeeMapper.selectOne(wrapper));
        if(optional.isPresent()){
            System.out.println(optional.get());
            return Result.fail("添加的咖啡名重复，请重新添加");
        }
        //查询到名字不是重复的，开始给id赋值
        coffee.setCofId(Uuid.getid());
        //插入数据，并返回结果
        boolean flag = save(coffee);
        if(flag){
            return Result.ok("添加成功");
        }
        return Result.fail("添加失败，查看日志");
    }

    @Override
    public Result select(String name, Integer page, Integer size) {
        // 创建分页对象
        Page<Coffee> pageInfo = new Page<>(page, size);
        // 创建查询条件
        QueryWrapper<Coffee> wrapper = new QueryWrapper<>();
        if (name != null && !name.trim().isEmpty()) {
            // 如果name不为空且非空白，则添加模糊查询条件
            wrapper.like("cof_name", name);
        }
        //筛选在售的
        wrapper.eq("state_id",StateEnum.ON_SALE.getStateId());
        // 执行分页查询
        IPage<Coffee> pageResult = super.page(pageInfo, wrapper);
        // 返回结果
        return Result.ok(pageResult);
    }

    @Override
    public Result update(Coffee coffee) {
        QueryWrapper<Coffee> wrapper = new QueryWrapper<>();
        //拿到coffee之后，查询名字是否有重复
        wrapper.eq("cof_name",coffee.getCofName());
        Optional<Coffee> optional = Optional.ofNullable(coffeeMapper.selectOne(wrapper));
        if(optional.isPresent()){
            System.out.println(optional.get());
            return Result.ok("修改的咖啡名重复，请重新修改");
        }
        //查询到修改的新名字不重复之后执行单条的修改
        boolean update = updateById(coffee);
        if (update) {
            return Result.ok("修改成功");
        }
        return Result.fail("修改失败");
    }
}
